
namespace KlearTweet.Client.Tab
{
    public class TabController
    {
        private readonly Initialization.AccountsManager _accountsManager;
        private readonly TabHeader _header;
        private readonly TabContent _content;
        private readonly Search.DataProvider _dataProvider;

        public TabController(Initialization.AccountsManager accountsManager, TabContainer container)
        {
            _accountsManager = accountsManager;
            _header = new TabHeader();
            _content = new TabContent();
            container.AddTab(_header, _content);

            _accountsManager.RegisterAddAccount(_content.EmptyPanel.AddAccount);
            _dataProvider = new Search.DataProvider(this, _header, _content.ListView, _accountsManager);
            new Search.OmniBoxController(_dataProvider, _accountsManager, _header);

            _content.EntitySource = _dataProvider.Entities;
            _content.ListView.EntityViewProvider = EntityViewProvider; // TODO: Use a more elequant solution

            _header.Loaded += (s, e) => FocusOnOmniBox();

            ShowEmptyPanelAndAccounts();
        }

        public void ShowEmptyPanelAndAccounts()
        {
            _content.EmptyPanel.Visibility = System.Windows.Visibility.Visible;
            _dataProvider.ShowAccounts();
        }

        public void HideEmptyPanel()
        {
            _content.EmptyPanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        public void FocusOnOmniBox()
        {
            _header.OmniBox.Focus();
        }

        private System.Windows.UIElement EntityViewProvider(Model.IEntity entity)
        {
            if (entity is Model.Account)
                return new DataPresentation.AccountController((Model.Account)entity, _dataProvider).View;
            if (entity is Model.Tweet)
                return new DataPresentation.TweetController(this, (Model.Tweet)entity).View;

            throw new System.NotSupportedException("Unknown entity: " + entity);
        }

        public System.Windows.Controls.HyperlinkButton GetLinkFor(string searchText)
        {
            var ctrl = new System.Windows.Controls.HyperlinkButton();
            if (searchText.StartsWith("http://", System.StringComparison.InvariantCultureIgnoreCase))
            {
                ctrl.NavigateUri = new System.Uri(searchText);
                ctrl.TargetName = "_blank";
            }
            else
                ctrl.Click += (s, e) =>
                                  {
                                      _header.OmniBox.Text = searchText;
                                      _dataProvider.SearchAsync(searchText);
                                  };
            return ctrl;
        }
    }
}